﻿using WebSelfHost.Utility.Core;
using WebSelfHost.Utility.ResponseModels;
using JinianNet.JNTemplate;
using Microsoft.AspNetCore.Mvc;
using WebSelfHost.Utility.Files;
using WebSelfHost.Utility.Extension;
#if !NETFRAMEWORK
using System;
using System.Collections.Generic;
using System.Text;
#else
using System.Web.Http;
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.AspNet.Identity.Owin;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
#endif


namespace WebSelfHost.Web.Controllers
{
#if !NETFRAMEWORK 
    public class BaseController : Controller
#else
    public class BaseController : ApiController
#endif
    {
#if NETFRAMEWORK
        protected ActionResult Content(string content)
        {
            return new ActionResult { Content = new StringContent(content, Encoding.UTF8, "text/plain") };
        }

        protected ActionResult ContentType(string content, string contentType)
        {
            return new ActionResult { Content = new StringContent(content, Encoding.UTF8, contentType) };
        }

        public new ActionResult Redirect(string url)
        {
            ActionResult resp = new ActionResult(HttpStatusCode.Moved);
            string originalString = Request.RequestUri.OriginalString;
            string pathAndQuery = Request.RequestUri.PathAndQuery;
            string baseUrl = originalString.Substring(0, originalString.IndexOf(pathAndQuery)); 
            resp.Headers.Location = new Uri(baseUrl + url);
            return resp;
        }

        protected ActionResult File(string virtualPath, string contentType)
        {
            return File(virtualPath, contentType, "HelloWorld");
        }

        protected ActionResult File(string virtualPath, string contentType, string fileDownloadName)
        {
            string physicalPath = MyEnvironment.WebRootPath(virtualPath);
            return PhysicalFile(physicalPath, contentType, fileDownloadName);
        }

        protected ActionResult PhysicalFile(string physicalPath, string contentType)
        {
            return PhysicalFile(physicalPath, contentType, "HelloWorld");
        }

        protected ActionResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName)
        {
            return File(System.IO.File.OpenRead(physicalPath), contentType, fileDownloadName);
        }


        protected ActionResult File(byte[] fileContents, string contentType)
        {
            return File(fileContents, contentType, "HelloWorld");
        }


        protected ActionResult File(byte[] fileContents, string contentType, string fileDownloadName)
        {
            ActionResult response = new ActionResult(HttpStatusCode.OK);
            response.Content = new ByteArrayContent(fileContents);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            response.Content.Headers.ContentLength = fileContents.Length;
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = HttpUtility.UrlEncode(fileDownloadName)
            };
            response.Headers.Add("Access-Control-Expose-Headers", "FileName");
            response.Headers.Add("FileName", HttpUtility.UrlEncode(fileDownloadName));
            return response;
        }

        protected ActionResult File(Stream fileStream, string contentType)
        {
            return File(fileStream, contentType, "HelloWorld");
        }

        protected ActionResult File(Stream fileStream, string contentType, string fileDownloadName)
        {
            ActionResult response = new ActionResult(HttpStatusCode.OK);
            response.Content = new StreamContent(fileStream);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            response.Content.Headers.ContentLength = fileStream.Length;
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = HttpUtility.UrlEncode(fileDownloadName)
            };
            response.Headers.Add("Access-Control-Expose-Headers", "FileName");
            response.Headers.Add("FileName", HttpUtility.UrlEncode(fileDownloadName));
            return response;
        }

#else
        protected ActionResult ContentType(string content, string contentType)
        {
            return Content(content, "text/html", Encoding.UTF8);
        }
#endif
        #region 快捷方法
        protected ActionResult Success(string message = "恭喜您，操作成功。", object data = null)
        {
            return Content(new AjaxResult(ResultType.Success, message, data).ToJson());
        }
        protected ActionResult Error(string message = "对不起，操作失败。", object data = null)
        {
            return Content(new AjaxResult(ResultType.Error, message, data).ToJson());
        }
        protected ActionResult Warning(string message, object data = null)
        {
            return Content(new AjaxResult(ResultType.Warning, message, data).ToJson());
        }
        protected ActionResult Info(string message, object data = null)
        {
            return Content(new AjaxResult(ResultType.Info, message, data).ToJson());
        }


#if NETFRAMEWORK
        public ActionResult Json(object obj)
        {
            return new ActionResult { Content = new StringContent(obj.ToJson(), Encoding.UTF8, "application/json") };
        }
#else
        public new ActionResult Json(object obj)
        {
            return new ContentResult() { ContentType = "application/json", Content = obj.ToJson() };
        }
#endif


        public ActionResult Text(string str)
        {
#if NETFRAMEWORK
            //return Content(str, "text/plain");
            return new ActionResult { Content = new System.Net.Http.StringContent(str, Encoding.UTF8, "text/plain") };
#else
            return new ContentResult() { ContentType = "text/plain", Content = str };
#endif
        }

        public ActionResult HtmlStr(string str)
        {
#if NETFRAMEWORK
            return new ActionResult { Content = new System.Net.Http.StringContent(str, Encoding.UTF8, "text/html") };
#else
            return Content(str, "text/html", Encoding.UTF8);
#endif
        }

        public ActionResult Html(string view)
        {
            return Html(view, null);
        }

        public ActionResult Html(string view, Dictionary<string, object> dict)
        {
            if (!view.StartsWith("/"))
                view = "/" + view;
            string path = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "Views";


            var template = Engine.LoadTemplate(path + view + ".html");


            if (dict != null)
            {
                foreach (KeyValuePair<string, object> keyValue in dict)
                {
                    template.Set(keyValue.Key, keyValue.Value);
                }
            }
            var result = template.Render();
#if NETFRAMEWORK
            // return Content(result, "text/html");
            return new ActionResult { Content = new System.Net.Http.StringContent(result, Encoding.UTF8, "text/html") };
#else
            return Content(result, "text/html", Encoding.UTF8);
#endif
        }
        #endregion
    }
}
#if NETFRAMEWORK
namespace Microsoft.AspNetCore.Mvc
{
    public class ActionResult : System.Net.Http.HttpResponseMessage
    {
        public ActionResult() : base(HttpStatusCode.OK)
        {

        }
        public ActionResult(HttpStatusCode statusCode) : base(statusCode)
        {
        }
    }
}
#endif